<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="isshow"
    width="550px"
  >
    <!--    TODO:树状列表后续操作-->
    <div class="dialogContent" v-loading="loading">
      <el-tree ref="tree" :data="treeData" node-key="fileId" :default-expanded-keys="expandedKeys" highlight-current
               :props="defaultProps" @node-click="nodeClick"
      >
        <div slot-scope="{data}" class="treeitem">
          <div class="treeimg">
            <img src="@/assets/image_library/dirsmall.png"/>
          </div>
          <div v-if="!data.update">{{ data.label }}</div>
          <div v-else>
            <el-input v-model="data.label" placeholder="请输入内容" @blur="(e) => updateLabel(e,data.fileId)"
                      ref="newLabel"
            ></el-input>
          </div>
        </div>
      </el-tree>
    </div>

    <span slot="footer" class="dialog-footer btns">
      <div>
        <el-button type="primary" @click="addPage">新建文件夹</el-button>
      </div>
      <div>
         <el-button @click="isshow = false">取 消</el-button>
         <el-button type="primary" @click="confirmUpdate">确 定</el-button>
      </div>

  </span>
  </el-dialog>
</template>
<script>
import {
  checkDuplicateFileName,
  checkgroupFileName,
  copyFile,
  createFolder,
  getFilePathTree,
  moveFile
} from '@/api/library_index'
import {
  getGroupFilePathTree,
  GroupcopyFile,
  GroupcreateFolder,
  GroupmoveFile
} from '@/api/library_groupList/groupList'
import { mapGetters } from 'vuex'

export default {
  name: 'movedialog',
  data() {
    return {
      isshow: false,
      dialogTitle: '选择复制到的位置',
      type: 'copy',
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      newFilePath: '',
      newParentId: '',
      ids: '',
      names: [],
      map: 2,
      groupId: '',
      fromType: '',
      nodeData: null,
      expandedKeys: [0],
      loading: true
    }
  },
  computed: {
    ...mapGetters('libraryFile', ['pathArr'])
  },
  methods: {
    show(type, ids, names, map, groupId) {
      this.type = type
      if (map) {
        this.fromType = 'group'
        this.map = map
        this.groupId = groupId
      }
      if (this.map == 1) {
        this.getGroupTree()
      } else {
        this.getTree()
      }
      if (type === 'copy') {
        this.dialogTitle = '选择复制到的位置'
      } else {
        this.dialogTitle = '选择移动到的位置'
      }
      this.ids = ids
      this.names = names
      this.isshow = true
    },
    randomString(length) {
      let str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
      let result = ''
      for (let i = length; i > 0; --i) {
        result += str[Math.floor(Math.random() * str.length)]
      }
      return result
    },
    addPage() {
      const newChild = {
        label: '新建文件夹',
        children: [],
        update: true,
        fileId: this.randomString(10)
      }
      this.$refs.tree.append(newChild, this.nodeData || this.treeData[0])
      this.expandedKeys = [newChild.fileId]
    },
    async getTree() {
      this.loading = true
      let res = await getFilePathTree({ isDir: 1 })
      if (res.code == 200) {
        this.treeData = [res.data]
        this.treeData[0].label = '我的文件'
      }
      this.loading = false
    },
    updateLabel(event, id) {
      let name = event.target.value
      this.treeData = this.changeTreeState(this.treeData, id)
      this.expandedKeys = [id]
      if (this.map == 1) {
        this.buildGroupDir(name, this.newFilePath || '/', this.newParentId || 0)
      } else {
        this.buildlibraryDir(name, this.newFilePath || '/', this.newParentId || 0)
      }
    },
    changeTreeState(arr, id) {
      return arr.map(item => {
        if (item.id === id) {
          item.update = false
        }
        if (item.children && item.children.length > 0) {
          item.children = this.changeTreeState(item.children, id)
        }
        return item
      })
    },
    // 获取群组文件树
    async getGroupTree() {
      this.loading = true
      let res = await getGroupFilePathTree({ groupId: this.groupId })
      if (res.code == 200) {
        this.treeData = [res.data]
        this.treeData = [res.data]
        this.treeData[0].label = '群文件'
      }
      this.loading = false
    },
    nodeClick(item, node) {
      if (node.data.update) {
        return
      }
      if (this.hasUpdate(this.treeData)) {
        return
      }
      this.nodeData = node
      this.newFilePath = item.filePath || '/'
      this.newParentId = item.fileId || 0
      if (this.newParentId != 0) {
        this.newFilePath == '/' ? this.newFilePath += item.label : this.newFilePath += `/${item.label}`
      }
    },
    // 判断树状结构里有没有在编辑
    hasUpdate(arr) {
      // 遍历数组
      for (let item of arr) {
        // 如果当前节点的 update 为 true，则返回 true
        if (item.update) {
          return true
        }
        // 如果有子节点，则递归调用
        if (item.children && item.children.length > 0) {
          if (this.hasUpdate(item.children)) {
            return true
          }
        }
      }
      return false
    },
    // 检测重名
    async checkName() {
      let res
      if (this.map == 1) {
        res = await checkgroupFileName({
          fileNameList: this.names.join(','),
          parentId: this.newParentId || 0,
          groupId: this.groupId
        })
      } else {
        res = await checkDuplicateFileName({ fileNameList: this.names.join(','), parentId: this.newParentId || 0 })
      }
      if (res.code == 200) {
        if (this.type == 'copy') {
          if (this.fromType === 'group') {
            this.groupCopyFiles()
          } else {
            this.copyFiles()
          }
        } else {
          if (this.fromType === 'group') {
            this.groupmoveFiles()
          } else {
            this.moveFiles()
          }
        }
      }
    },
    confirmUpdate() {
      this.checkName()
    },

    // 移动
    async moveFiles() {
      let res = await moveFile({
        ids: this.ids.join(','),
        newFilePath: this.newFilePath,
        newParentId: this.newParentId || 0
      })
      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: '移动成功!'
        })
        this.isshow = false
        console.log(this.$parent.dataList, 'jkjlp;ppppp')
        this.$parent.dataList ? this.$parent.uploadNewFile() : this.$parent.getFilesList(this.pathArr[this.pathArr.length - 1].id)
      }
    },
    // 复制
    async copyFiles() {
      let res = await copyFile({
        ids: this.ids.join(','),
        newFilePath: this.newFilePath,
        newParentId: this.newParentId || 0
      })
      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: '复制成功!'
        })
        this.isshow = false
        this.$parent.dataList ? this.$parent.uploadNewFile() : this.$parent.getFilesList(this.pathArr[this.pathArr.length - 1].id)
      }
    },
    // 群复制
    async groupCopyFiles() {
      let res = await GroupcopyFile({
        ids: this.ids.join(','),
        newFilePath: this.newFilePath,
        newParentId: this.newParentId || 0,
        groupId: this.groupId,
        copyType: this.map
      })
      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: '复制成功!'
        })
        this.isshow = false
        this.$parent.dataList ? this.$parent.uploadNewFile() : this.$parent.getFilesList(this.pathArr[this.pathArr.length - 1].id, this.groupId)
      }
    },
    // 群移动
    async groupmoveFiles() {
      let res = await GroupmoveFile({
        ids: this.ids.join(','),
        newFilePath: this.newFilePath,
        newParentId: this.newParentId || 0,
        groupId: this.groupId
      })
      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: '移动成功!'
        })
        this.isshow = false
        this.$parent.dataList ? this.$parent.uploadNewFile() : this.$parent.getFilesList(this.pathArr[this.pathArr.length - 1].id, this.groupId)
      }
    },
    // 新建资源库文件夹
    async buildlibraryDir(fileName, filePath, parentId) {
      let res = await createFolder({ fileName: fileName, filePath: filePath, parentId: parentId })
      if (res.code == 200) {
        this.$message.success('新建成功')
        this.getTree()
        setTimeout(() => {
          this.expandedKeys = [res.data.id]
        }, 500)
      }
    },
    // 新建群组文件夹
    async buildGroupDir(fileName, filePath, parentId) {
      let res = await GroupcreateFolder({
        groupId: this.groupId,
        fileName: fileName,
        filePath: filePath,
        parentId: parentId
      })
      if (res.code == 200) {
        this.$message.success('新建成功')
        this.getGroupTree()
        setTimeout(() => {
          this.expandedKeys = [res.data.id]
        }, 500)

      }
    }
  }
}

</script>
<style scoped lang="scss">
::v-deep .el-input--medium .el-input__inner {
  height: 25px !important;
}

.dialogContent {
  width: 100%;
  height: 400px;
  overflow: scroll;
}

.treeitem {
  display: flex;
  align-items: center;
}

.treeimg {
  width: 15px;
  height: 16px;

  img {
    width: 15px;
    height: 16px;
  }

  margin-right: 5px;
}

.btns {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
